<?php
/**
 * https://gitee.com/Mao02
 * http://blog.dazhetu.cn/
 * jay_fun 410136330@qq.com
 * Date: 2018/4/9 0009
 * Time: 上午 0:45
 */

namespace app\admin\controller;

use app\common\controller\BasicAdmin;
use think\Db;
use think\exception\PDOException;
use think\facade\Request;

/**
 * @title 后台管理员
 * Class Admin
 * @package app\admin\controller
 */
class Admin extends BasicAdmin
{
    
    protected $table = "SystemAdmin";

    /**
     * @title 列表页
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $db = Db::name($this->table)->where('is_deleted','=',0);
        return $this->_list($db);
    }
    
    /**
     * @title 添加
     * @return mixed
     */
    public function add()
    {
        return $this->_form('', 'form');
    }

    /**
     * 添加前置
     * @param $data
     */
    public function _add_form_before(&$data){
        if (Request::isPost()){
            empty($data['name'])&&$this->error('请输入姓名');
            (strlen($data['username'])<6)&&$this->error('用户名长度必须大于6位');
            $uid = Db::name($this->table)->where('username',$data['username'])->value('id');
            $uid&&$this->error("已经存在的用户名");
            !preg_match('/^[a-zA-Z0-9]+$/',$data['username'])&&$this->error('只能使用字母数字');
            $data['create_time'] = Request::time();
        }
    }

    /**
     * @title 编辑
     * @return array|mixed|null|\PDOStatement|string|\think\Model
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        return $this->_form('', 'form');
    }

    /**
     * 编辑前置
     * @param $data
     */
    protected function _edit_form_before(&$data)
    {
        (intval($data['id']) === 1) && $this->error("超级用户禁止修改！");
    }

    /**
     * @title 删除
     * @throws PDOException
     * @throws \think\Exception
     */
    public function del()
    {
        $ids = Request::get('ids');
        $idarr = explode(',',$ids);
        if(in_array('1',$idarr)){
            $this->error("超级用户禁止删除！");
        }
        $this->_del($ids);
    }

    /**
     * @title 重置密码
     * @return array|mixed|null|\PDOStatement|string|\think\Model
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function password()
    {
        return $this->_form('', 'password');
    }

    /**
     * 设置密码前置
     * @param $data
     */
    protected function _password_form_before(&$data)
    {
        if (Request::isPost()) {
            $password = $data['password'];
            $repassword = $data['repassword'];

            (strlen($password) < 5 || strlen($password) > 25) && $this->error('密码长度必须5-25位之间');
            !preg_match('/^[a-zA-Z0-9]+$/', $password) && $this->error('只能使用字母数字');
            ($password !== $repassword) && $this->error('两次密码输入不一致');
            unset($data['repassword']);
            $option = [
                'cost'=>config('password.cost')
            ];
            $data['password'] = password_hash($data['password'],PASSWORD_DEFAULT, $option);
        }
    }

    /**
     * @title 授予角色
     * @return mixed
     * @throws PDOException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function role()
    {
        if (Request::isGet()) {
            $id = Request::get('id');
            $roles = Db::name('SystemRole')->select();
            $access = Db::name('SystemAuthMap')
                ->where('admin_id', $id)
                ->column('role_id');
            $this->assign([
                'roles' => $roles,
                'access' => $access,
                'id' => $id
            ]);
            return $this->fetch();
        } elseif (Request::isPost()) {
            $roles = Request::post('role/a');
            $id = Request::post('id');
            $insert = [];
            if (empty($roles)) {
                Db::name('SystemAuthMap')
                    ->where('admin_id', $id)
                    ->delete();
                $this->success("操作成功！", '');
            }
            foreach ($roles as $key => $role) {
                $insert[] = ['admin_id' => $id, 'role_id' => $key];
            }
            Db::startTrans();
            try {
                $res1 = Db::name('SystemAuthMap')
                    ->where('admin_id', $id)
                    ->delete();
                $res2 = Db::name('SystemAuthMap')->insertAll($insert);
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error("操作失败！", '', $e);
            }
            $this->success("操作成功！", '');
        }
    }

    /**
     * @title 禁用/启用操作
     * @throws PDOException
     * @throws \think\Exception
     */
    public function change()
    {
        $id = Request::get('id');
        (intval($id) === 1) && $this->error("超级用户禁止禁用！");
        $state = Request::get('state');
        $this->_change($id, ['state' => $state]);
    }
}